<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/utils/request.js'

export default {
  name: 'UploadNovel',
  components: {
    Plus
  },
  setup() {
    const formRef = ref(null)
    const form = reactive({
      title: '',
      author_name: '',
      description: '',
      avatar: '',
      category: '',
      publish_time: ''
    })

    const categories = ref([])

    const rules = reactive({
      title: [{ required: true, message: '请输入小说名称', trigger: 'blur' }],
      author_name: [{ required: false, message: '请输入作者名称', trigger: 'blur' }],
      description: [{ required: false, message: '请输入小说简介', trigger: 'blur' }],
      avatar: [{ required: false, message: '请上传封面', trigger: 'change' }],
      category: [{ required: false, message: '请选择分类', trigger: 'blur' }],
      publish_time: [{ required: false, message: '请输入年份', trigger: 'blur' }]
    })

    const handleAvatarChange = async (file) => {
      const formData = new FormData()
      formData.append('file', file.raw)

      try {
        const uploadResponse = await request.post('/upload', formData
        )

        if (uploadResponse.code === 1) {
          form.avatar = uploadResponse.data
          ElMessage.success('封面上传成功')
        } else {
          ElMessage.error(uploadResponse.msg || '封面上传失败')
        }
      } catch (error) {
        ElMessage.error('服务异常')
      }
    }

    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        ElMessage.error('上传封面图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('上传封面图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }

    const submitForm = (formEl) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (valid) {
          const formData = {
            title: form.title,
            authorName: form.author_name,
            description: form.description,
            avatar: form.avatar,
            category: form.category,
            publishTime: form.publish_time
          }

          request.post('/novel/add', formData
          ).then((response) => {
            if (response.code === 1) {
              ElMessage.success('上传成功')
            } else {
              ElMessage.error(response.msg || '上传失败')
            }
          }).catch((error) => {
            ElMessage.error('服务异常')
          })
        } else {
          ElMessage.error('请检查表单信息')
          return false
        }
      })
    }

    const resetForm = (formEl) => {
      if (!formEl) return
      formEl.resetFields()
    }

    const getCategories = async () => {
      try {
        const response = await request.get('/category')
        if (response.code === 1) {
          categories.value = response.data
        } else {
          ElMessage.error(response.msg || '获取分类失败')
        }
      } catch (error) {
        ElMessage.error('服务异常')
      }
    }

    onMounted(() => {
      getCategories()
    })

    return {
      formRef,
      form,
      categories,
      rules,
      handleAvatarChange,
      beforeAvatarUpload,
      submitForm,
      resetForm
    }
  }
}
</script>

<template>
  <div class="upload-novel">
    <h2>上传小说</h2>
    <el-form :model="form" label-width="100px" ref="formRef" :rules="rules">
      <el-form-item label="小说名称" prop="title">
        <el-input v-model="form.title" placeholder="请输入小说名称" required></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="author_name">
        <el-input v-model="form.author_name" placeholder="请输入作者名称"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="description">
        <el-input v-model="form.description" type="textarea" placeholder="请输入小说简介"></el-input>
      </el-form-item>
      <el-form-item label="上传封面" prop="avatar">
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :on-change="handleAvatarChange"
          :before-upload="beforeAvatarUpload"
          :auto-upload="false"
        >
          <el-image
            v-if="form.avatar"
            style="width: 178px; height: 178px"
            :src="form.avatar"
            fit="cover"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="form.category" placeholder="请选择分类" clearable filterable style="width: 200px;">
          <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.name" />
        </el-select>
      </el-form-item>
       <el-form-item label="发布">
        <el-select v-model="form.publish_time" placeholder="请选择或输入出版时间" clearable filterable style="width: 200px;">
          <el-option v-for="year in Array.from({ length: 110 }, (_, i) => new Date().getFullYear() - i)" :key="year" :label="year" :value="year.toString()" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
        <el-button @click="resetForm(formRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.upload-novel {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>